package store

import (
	"database/sql"
	"log"
	"path"
	"time"

	// init sqlite3
	_ "github.com/mattn/go-sqlite3"
	uuid "github.com/satori/go.uuid"
	"smartconn.cc/tosone/ra_main/common"
	"smartconn.cc/tosone/ra_main/config"
	"smartconn.cc/tosone/ra_main/taskMgr"
)

const bookSchema = "(\"bookID\" TEXT, \"serverBookID\" TEXT, \"feature\" TEXT, \"count\" INTEGER, \"date\" TEXT, \"version\" TEXT, \"isDefault\" TEXT, \"author\" TEXT, \"title\" TEXT)"
const bookSchemaPure = "(\"bookID\", \"serverBookID\", \"feature\", \"count\", \"date\", \"version\", \"isDefault\", \"author\", \"title\")"

const modelSchema = "(\"id\" INTEGER, \"mode\" TEXT, \"role\" TEXT)"
const modelSchemaPure = "(\"id\", \"mode\", \"role\")"

const taskSchema = "(\"id\" TEXT, \"name\" TEXT, \"taskContent\" TEXT)"
const taskSchemaPure = "(\"id\", \"name\", \"taskContent\")"

const tipsAudioSchema = "(\"hash\" TEXT, \"path\" TEXT)"
const tipsAudioSchemaPure = "(\"hash\", \"path\")"

func init() {
	major, err = sql.Open("sqlite3", path.Join(config.DatabasePath, config.MajorDB))
	if err != nil {
		log.Println(err)
		return
	}
	_, err = major.Exec("CREATE TABLE IF NOT EXISTS \"model\" " + modelSchema)
	if err != nil {
		log.Println(err)
		return
	}
	var id int
	err = major.QueryRow("SELECT \"id\" FROM \"model\" WHERE \"id\"=1").Scan(&id)
	switch {
	case err == sql.ErrNoRows:
		_, err = major.Exec("INSERT INTO \"model\" "+modelSchemaPure+" VALUES "+paramsNums(modelSchema), 1, "default", uuid.NewV4().String())
	case err != nil:
		log.Println(err)
		return
	}
	_, err = major.Exec("CREATE TABLE IF NOT EXISTS \"book\" " + bookSchema)
	if err != nil {
		log.Println(err)
		return
	}
	_, err = major.Exec("CREATE TABLE IF NOT EXISTS \"task\" " + taskSchema)
	if err != nil {
		log.Println(err)
		return
	}
	_, err = major.Exec("CREATE TABLE IF NOT EXISTS \"tipsAudio\" " + tipsAudioSchema)
	if err != nil {
		log.Println(err)
		return
	}
	err = major.QueryRow("SELECT \"mode\",\"role\" FROM \"model\" WHERE \"id\"=1").Scan(&currMode, &currRole)
	if err != nil {
		log.Println(err)
		return
	}
}

// SetCurrMode 设置当前的 Mode
func SetCurrMode(m string) {
	_, err := major.Exec("UPDATE \"model\" SET \"mode\"=" + m + " WHERE id=1")
	if err != nil {
		log.Println(err)
		return
	}
	currMode = m
}

// GetCurrMode 得到当前的模式
func GetCurrMode() string {
	return currMode
}

// SetCurrRole 设置当前的 Role
func SetCurrRole(r string) {
	_, err := major.Exec("UPDATE \"model\" SET \"role\"=" + r + " WHERE id=1")
	if err != nil {
		log.Println(err)
		return
	}
	currRole = r
}

// GetCurrRole 获取当前的角色
func GetCurrRole() string {
	return currRole
}

// UpdateBookCount 更新书的阅读次数
func UpdateBookCount(bookID string, count int) {
	_, err = major.Exec("UPDATE \"book\" set \"count\"=? where \"bookID\"=?", count, bookID)
	if err != nil {
		log.Println(err)
		return
	}
}

// SetBook 设置故事
func SetBook(param map[string]string) {
	err = major.QueryRow("SELECT * from \"book\" WHERE \"bookID\"=" + param["bookID"]).Scan()
	switch {
	case err == sql.ErrNoRows:
		major.Exec("INSERT INTO \"book\" "+bookSchemaPure+" VALUES "+paramsNums(bookSchema), param["bookID"], param["serverBookID"], 0, time.Now().Format(time.RFC3339), param["version"], param["isDefault"], param["title"])
	case err != nil:
		log.Println(err)
	default:
		log.Println("Error: Insert into \"book\" error due to book exist.")
	}
}

// GetBookCovers 获取所有的封面特征值
func GetBookCovers() (covers []common.FeatureWithID) {
	rows, err := major.Query("SELECT \"feature\",\"BookID\" FROM \"book\"")
	if err != nil {
		log.Println(err)
		return
	}
	var feature, BookID string
	for rows.Next() {
		err := rows.Scan(&feature, &BookID)
		if err != nil {
			log.Println(err)
			return
		}
		covers = append(covers, common.FeatureWithID{Feature: feature, ID: BookID})
	}
	return
}

// AddTask 添加任务
func AddTask(name, taskContent string) {
	_, err = major.Exec("INSERT INTO \"task\" "+taskSchemaPure+" VALUES "+paramsNums(taskSchema), common.UUID, name, taskContent)
	if err != nil {
		log.Println(err)
		return
	}
	taskMgr.Trigger(name)
}

// RemoveTask 移除任务
func RemoveTask(id string) {
	_, err = major.Exec("DELETE FROM \"task\" WHERE \"id\"=?", id)
	if err != nil {
		log.Println(err)
		return
	}
}

// GetATask 获取一个任务
func GetATask(name string) (id, taskContent string, err error) {
	err = major.QueryRow("SELECT * from \"task\" WHERE \"name\"=?", name).Scan(&id, &taskContent)
	return id, taskContent, err
}

// IsTipsAudioExist IsTipsAudioExist
func IsTipsAudioExist(hash string) string {
	var p string
	err = major.QueryRow("SELECT \"path\" from \"tipsAudio\" WHERE \"hash\"=?", hash).Scan(&p)
	if err == sql.ErrNoRows {
		return ""
	}
	return p
}

// AddTipsAudio AddTipsAudio
func AddTipsAudio(h, p string) {
	_, err = major.Exec("INSERT INTO \"tipsAudio\" "+tipsAudioSchemaPure+" VALUES "+paramsNums(tipsAudioSchema), h, p)
	if err != nil {
		log.Println(err)
		return
	}
}

//DelTipsAudio DelTipsAudio
func DelTipsAudio() {
	_, err = major.Exec("DELETE FROM \"tipsAudio\"")
	if err != nil {
		log.Println(err)
		return
	}
}
